package com.rw.tool.util.expression.expression.parser.element;

import com.rw.tool.util.expression.element.ExpressionElement;
import com.rw.tool.util.expression.element.NumberElement;
import com.rw.tool.util.string.StringScanner;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;

/**
 * 数字类型处理
 */
public class NumberElementParser extends ElementParser<NumberElement> {
    public NumberElementParser() {
        super(NumberElement.class);
    }

    @Override
    public Optional<ExpressionElement> handler(StringScanner scanner, int scale) {
        // 如果当前状态能接受数字类型，则扫描数字类型
        if (scanner.hasNextNumber()) {
            BigDecimal number = scanner.nextNumber();
            // 设置精度
            if (scale >= 0) {
                number = number.setScale(scale, RoundingMode.HALF_UP);
            }
            return Optional.of(new NumberElement(number));
        }

        return Optional.empty();
    }
}
